import type { ValidResultEntry } from '../interfaces'
import { ThemeVarService } from '../../lib/abstract/style/theme_var/service'
import { MESSAGE_STYLES, SYMBOLS } from '../interfaces'
import { APP_STYLES } from './app_style'
import { BODY_SELECTOR, PROJECT_PREFIX } from './base'
import {
  AppStyleCollections,
  BADGE_CLASS_STYLES,
  DRAG_HANDLE_CLASS_STYLES,
  LINK_ICON_CLASS_STYLES,
  SEARCH_META_CLASS_STYLES,
  TOOL_CLASS_STYLES,
} from './module_config'
import { StylesService } from './styles'
import { ButtonStyleHelper } from './styles/button'
import { getAnimationCSS } from './styles/keyframes'
import { MODULE_RESPONSIVE_STYLES } from './styles/responsive'
import { generateAllTitleThemes, getAllTitleSelector } from './styles/title'

// =============================== 【基础配置】 ===============================
export const IS_PRODUCTION = false
export const APP_CONFIG: {
  minifyCSS: boolean
  minifyJS: boolean
  logLevel: string
  selectionListener: boolean
  validateConfig: boolean
} = {
  minifyCSS: IS_PRODUCTION,
  minifyJS: IS_PRODUCTION,
  logLevel: IS_PRODUCTION ? 'warn' : 'info',
  selectionListener: false,
  validateConfig: !IS_PRODUCTION,
}

// =============================== 【应用级】 ===============================
export const MAX_Z_INDEX: number = 2 ** 31 - 1
export const EMPTY_FUNCTION: () => void = () => {}

// 存储类型
export enum StorageType {
  GMStorage = 'GMStorage',
  localStorage = 'localStorage',
}

export const getCurrentHostname: () => string = () => window.location.hostname
export const getCurrentOrigin: () => string = () => window.location.origin
export const getCurrentURL: () => string = () => window.location.href
export const getCurrentSearch: () => string = () => window.location.search

// 元素白名单
export const ELEMENT_WHITE_SELECTORS: string[] = [
  '.swal2-modal.user-center-modal',
]
// 分类显示名称映射
export const FEATURE_CATEGORIES_NAME: Record<FeatureCategory, string> = {
  appearance: '界面美化',
  interaction: '交互优化',
  navigation: '快捷导航',
  content: '内容控制',
  dataPresentation: '数据展示',
  privacy: '隐私保护',
  unknown: '未知分类',
}

export const VALID_RESULT: Record<Uppercase<ValidResultType>, ValidResultEntry> = {
  VALID: {
    value: 'valid',
    symbol: SYMBOLS.COLOR_CIRCLES.GREEN,
    color: '#4CAF50',
  },
  INVALID: {
    value: 'invalid',
    symbol: SYMBOLS.COLOR_CIRCLES.RED,
    color: '#F44336',
  },
  SKIP: {
    value: 'skip',
    symbol: SYMBOLS.COLOR_CIRCLES.WHITE,
    color: '#9E9E9E',
  },
}

export function getValidSymbol(value: ValidResultType): string {
  const result = VALID_RESULT[value.toUpperCase() as Uppercase<ValidResultType>]
  return result ? result.symbol : SYMBOLS.COLOR_CIRCLES.WHITE
}

/**
 * GM 注册样式注释
 */
export const GM_STYLE_COMMENT: string = `${PROJECT_PREFIX}-gm 注册样式`

/**
 * 获取 GM Style 标签
 */
export function getGmStyleElements(): HTMLStyleElement[] {
  return Array.from(document.head.querySelectorAll('style'))
    .filter((element): element is HTMLStyleElement => {
      const styleElement = element as HTMLStyleElement
      return (styleElement.textContent?.includes(GM_STYLE_COMMENT)) ?? false
    })
}

/**
 * 添加 GM 注册样式
 */
export function addGmStyle(): void {
  GM_addStyle(`
    /* ${GM_STYLE_COMMENT} */
    :root {
      font-size: var(--root-font-size) !important;
    }
    
    /* ================================= 动画样式 ================================= */
    ${getAnimationCSS()}

    ${BODY_SELECTOR} {
      /* ============================ 第三方 ============================*/
      ${APP_STYLES.swal2}
      /*按钮禁用*/
      button[disabled]{
        cursor: not-allowed !important;
        opacity: 0.65 !important;
        pointer-events: none !important;
        filter: grayscale(30%) !important;
      }

      /* =============================== 【工具类】 =============================== */
      ${BADGE_CLASS_STYLES}
      ${TOOL_CLASS_STYLES}
      ${SEARCH_META_CLASS_STYLES}
      ${DRAG_HANDLE_CLASS_STYLES}
      ${LINK_ICON_CLASS_STYLES}
      
      /* =============================== 【基础样式】 =============================== */
      /* 清除所有用户选择限制 */
      * {
        ${StylesService.getInstance().selection.allow}
      }
      
      &.${AppStyleCollections.Drag.NO_SELECTION} {
        ${StylesService.getInstance().selection.prevent}
        cursor: default !important;
        
        * {
          ${StylesService.getInstance().selection.prevent}
        }
      }
      
      /* 选中文本 */
      ::selection {
        background-color: var(${ThemeVarService.getInstance().selection.background}) !important;
        color: var(${ThemeVarService.getInstance().selection.text}) !important;
      }
      
      /* 强调文本 */
      ${AppStyleCollections.Search.value.HIGHLIGHT_TAG}.${AppStyleCollections.Search.class.HIGHLIGHT_CLASS} {
        color: var(${ThemeVarService.getInstance().em.text}) !important;
        font-style: normal !important;
      }
      
      /* ================================= 按钮样式 ================================= */
      ${ButtonStyleHelper.generateButtonStyles()}
      
      /* ================================= 【标题样式】 ================================= */    
      ${generateAllTitleThemes()}

      ${getAllTitleSelector()} {
        /* 去掉标题左、右边距 */
        margin-left: 0 !important;
        margin-right: 0 !important;
      }

      /* ================================= 消息样式 ================================= */
      ${Object.values(MESSAGE_STYLES).map(style => `
        .${style.className} {
          color: ${style.color} !important;
          background-color: ${style.bgColor} !important;
          border-color: ${style.borderColor} !important;
        }
      `).join('')}
      
      /* =============================== 【响应式处理】 =============================== */
      ${MODULE_RESPONSIVE_STYLES}
    }
  `)
}
